#!/usr/bin/python
import commands, os, sys, re

def executeCommand(cmd, args=[], ignoreOnError=False):
    for arg in args:
        cmd = cmd + ' ' + str(arg)
    try:
        result = commands.getstatusoutput(cmd)
    except Exception as errmsg:
        return 1, 'Exception caught - ' + str(errmsg)
    if result[0] != 0 and ignoreOnError == False:
        raise Exception("Failed to execute command: " + cmd)
    return result[0] >> 8 , result[1]

nagiosHosts = 0
nagiosServices = 0
nagios_snmp_monitors = 0
snmp_monitd_monitors = 0
nagios_esx_monitors = 0
nagios_interface_monitors = 0

status, _ = executeCommand('service nagios status', [], True)
if status != 0:
    print "Monitoring service not running."
    sys.exit(2)

if os.path.isdir("/opt/snmp-monitd/"):
    hasPythonInterface = True
    snmp_monitd_monitors = executeCommand("/bin/grep -o -r \"<monitor>\" /var/lib/monitd/conf/* | wc -l", [], True)[1]
else:
    hasPythonInterface = False

try:
    nagios_snmp_monitors = executeCommand("/bin/grep -r check_snmp /nems/nagios/etc/SA/* | wc -l", [], True)[1]
    nagios_interface_monitors = executeCommand("/bin/grep -r check_snmp_int /nems/nagios/etc/SA/* | wc -l", [], True)[1]
    nagios_esx_monitors = executeCommand("/bin/grep -r check_esx /nems/nagios/etc/SA/* | wc -l", [], True)[1]
except Exception, emsg:
    print ('Error - ' + str(emsg))
    sys.exit(2)

stats = executeCommand("/nems/nagios/bin/nagiostats |grep \"Total Hosts\|Total Services\"", [], True)[1]
for line in stats.split("\n"):
    line = line.strip()
    if line.startswith("Total Hosts:"):
        matched = re.match("Total Hosts:\s+(\d+)", line)
        if matched:
            nagiosHosts = matched.group(1)
        
    if line.startswith("Total Services:"):
        matched = re.match("Total Services:\s+(\d+)", line)
        if matched:
            nagiosServices = matched.group(1)
    
print
print "Total Hosts - " + str(nagiosHosts)
print "Total Monitors - " + str(int(nagiosServices) + int(snmp_monitd_monitors))
print "SNMP Monitors - " + str(int(nagios_snmp_monitors) + int(snmp_monitd_monitors))
print "Interface Monitors - " + str(int(nagios_interface_monitors) + int(snmp_monitd_monitors))
print "VMware Monitors - " + str(nagios_esx_monitors)
print